local addon = AspireML
local BidsGui = addon:NewModule("BidsGui", "AceConsole-3.0", "AceEvent-3.0")
local AceGUI = LibStub("AceGUI-3.0")

-- Upvalues
local _G = _G


function BidsGui:OnInitialize()
	-- something	
end

function BidsGui:OnEnable()
	self:RegisterMessage( "AspireML_StartBid", "StartBid" );
	self:RegisterMessage( "AspireML_StartRoll", "StartRoll" );
	self:RegisterMessage( "AspireML_UpdateBids", "UpdateBids" );
	self:RegisterMessage( "AspireML_CloseBid", "CloseBid" );
	
	self.timer = CreateFrame( "Frame", "TimerFrame" )
	self.timer:SetScript( "OnUpdate", nil )
	
	self.attempts = 10
	self.buttons = 0	
	self.scrollbars = 0
	self.numentries = 0
	self.selected = nil
		
end


function BidsGui:StartBid( arg1, arg2 )
	-- Arg1: addon_StartBid, Arg2: Itemlink
	BidsGui:HideFrame()
	
	-- Open GUI window
	BidsGui.item = AspireML:ParseItem(arg2);
	
	if AspireML.masterlooter then
		BidsGui:ShowFrame()
	end
end

function BidsGui:StartRoll( arg1, arg2 )
	-- Arg1: addon_StartBid, Arg2: Itemlink
	BidsGui:HideFrame()
	
	-- Open GUI window
	BidsGui.item = AspireML:ParseItem(arg2);
	BidsGui:ShowFrame()
end

function BidsGui:CloseBid( )
	-- Close GUI window
	BidsGui:HideFrame()
end

function BidsGui:UpdateBids()	
	if self.frame and AspireML.bids then
	
		for _, entry in pairs( self.frame.entries ) do
			entry.bid = nil
			entry:Hide()
		end	
		
		local entry_idx = 1
	
		for _,bid in pairs(AspireML.bids) do
					
			local entry = self.frame.entries[entry_idx]
								
			entry.line1:SetText( "[" .. AspireML:GetColoredName( bid.player ).. "]: " .. bid.message )
			entry.bid = bid;
			entry:Show()
			
			entry_idx = entry_idx + 1
		end	
		
	end
end


function BidsGui:ShowFrame()

	if BidsGui.item and BidsGui.item.link then
		
		self:CreateFrame()	
		
		self:UpdateBids()	
		
		self.frame.image:SetTexture( BidsGui.item.texture );				
		self.frame.image:SetTexCoord(0, 1, 0, 1)
		self.frame.image:Show()
		self.frame.label:SetText( BidsGui.item.link )
		self.frame.label:SetHeight( 32 )
		self.frame.topframe:Show()
		
		self.attempts = 10
	
	-- sometimes the biditem isn't available yet
	elseif self.attempts > 0 then
	 
	 	self.elapsed = 0
	 	self.attempts = self.attempts - 1
		
		self.timer:SetScript( "OnUpdate", function( event, elapsed )
			
			BidsGui.elapsed = BidsGui.elapsed + elapsed
			if BidsGui.elapsed >= 0.5 then
				BidsGui.timer:SetScript( "OnUpdate", nil )
				BidsGui:ShowFrame()
			end
		end)
	
	end

end

function BidsGui:HideFrame()
	
	if self.frame then
		-- save width
		AspireML.db.global.window.width = self.frame.topframe:GetWidth()
		AspireML.db.global.window.height = self.frame.topframe:GetHeight()	
		
		AspireML.db.global.window.point,
		_,
		AspireML.db.global.window.relativePoint,
		AspireML.db.global.window.x, 
		AspireML.db.global.window.y = self.frame.topframe:GetPoint()		
				
		self.frame.topframe:Hide()
	end
	
	self.attempts = 10
	self.timer:SetScript( "OnUpdate", nil )
end

function BidsGui:CreateFrame()

	local topframe, ilabel, image, label, blist, broll, braidroll, bclose, scroller, scrollcontainer

	-- frame already created return
	if BidsGui.frame then return end
	
	topframe = self:CreateTopFrame()
	
	-- icon + label
	ilabel, image, label = self:CreateIconAndLabel( topframe )
	ilabel:SetPoint( "TOPLEFT", topframe, "TOPLEFT", 15, -15 )
	ilabel:SetPoint( "TOPRIGHT", topframe, "TOPRIGHT", -10, -15 )
	
	ilabel:SetScript( "OnEnter", function()	
		if AspireML.biditem and AspireML.biditem.link then	
			GameTooltip:SetOwner( ilabel, "ANCHOR_CURSOR" );
			GameTooltip:SetHyperlink( AspireML.biditem.link );
			GameTooltip:Show();
		end
	end)	
	ilabel:SetScript( "OnLeave", function()		
		GameTooltip:Hide()
	end)
	
	-- List Bids Button
	blist = self:CreateButton( "List Bids" )
	blist:SetWidth(90)	
	blist:SetScript("OnClick", function() AspireML:SendMessage("AspireML_ListBids") end)		
	blist:SetParent( topframe )
	blist:SetPoint( "BOTTOMLEFT", topframe, "BOTTOMLEFT", 10, 10 )
	
	-- Players roll
	broll = self:CreateButton( "Players Roll" )
	broll:SetWidth(120)
	broll:SetScript("OnClick", function() AspireML:SendMessage("AspireML_StartRoll", BidsGui.item.link) end)
	broll:SetParent( topframe )
	broll:SetPoint( "TOPLEFT", blist, "TOPRIGHT" )
	if not AspireML.masterlooter then 
		broll:Disable()
	end	
	
	-- Raidroll
	braidroll = self:CreateButton( "Raid Roll" )
	braidroll:SetWidth(110)
	braidroll:SetParent( topframe )
	braidroll:SetPoint( "TOPLEFT", broll, "TOPRIGHT" )
	if not AspireML.masterlooter then 
		braidroll:Disable( true )
	end
	braidroll:SetScript("OnClick", function() 
		AspireML:SendMessage("AspireML_CloseBid")
		AspireML:SendMessage("AspireML_StartRaidRoll", BidsGui.item.link) 		
	end)
	
	-- close
	bclose = self:CreateButton( "Close" )
	bclose:SetWidth(100)
	bclose:SetParent( topframe )
	bclose:SetPoint( "TOPLEFT", braidroll, "TOPRIGHT", 5, 0 )
	bclose:SetScript("OnClick", function() 
		if AspireML.masterlooter then
			if BidsGui.selected and BidsGui.selected.bid then 		
				if AspireML.mode == "bid" or AspireML.mode == "roll" then								
					AspireML:Handout(AspireML.biditem.string, BidsGui.selected.bid.player)
				end		
			end
		
			AspireML:SendMessage("AspireML_CloseBid")
		else
			BidsGui:HideFrame()
		end
	end)
	
	-- scroller
	scrollframe, scrollcontainer = self:CreateScrollFrame( topframe )
	scrollframe:SetPoint("TOPLEFT", topframe, "TOPLEFT", 10, -55)
	scrollframe:SetPoint("BOTTOMRIGHT", topframe, "BOTTOMRIGHT", -34, 35)


	BidsGui.frame = {}	
	BidsGui.frame.topframe = topframe
	BidsGui.frame.scrollframe = scrollframe
	BidsGui.frame.scrollcontainer = scrollcontainer
	BidsGui.frame.ilabel = ilabel
	BidsGui.frame.image = image
	BidsGui.frame.label = label
	BidsGui.frame.entries = {}

	-- entries
	local lastentry = nil
	for i = 1, 40 do
		entry = self:CreateBidEntry( scrollcontainer, lastentry )
		entry.idx = i
		lastentry = entry
		table.insert( BidsGui.frame.entries, entry )
	end

	
	-- reset scroller
	self:SetScroll( 0 )
end



------------------------------------------------------------
--                                                        --
--       Initialization and creation of the gui           --
--                                                        --
------------------------------------------------------------
function BidsGui:CreateTopFrame()

	local FrameBackdrop = {
		bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
		edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
		tile = true, tileSize = 32, edgeSize = 32,
		insets = { left = 8, right = 8, top = 8, bottom = 8 }
	}

	frame = CreateFrame("Frame", nil, UIParent)
	frame:Hide()
	frame:EnableMouse(true)
	frame:SetMovable(true)
	frame:SetResizable(true)
	frame:SetFrameStrata("FULLSCREEN_DIALOG")
	frame:SetBackdrop(FrameBackdrop)
	frame:SetBackdropColor(0, 0, 0, 1)
	frame:SetMinResize(445, 250)
	frame:SetToplevel(true)	
	frame:SetWidth( AspireML.db.global.window.width )
	frame:SetHeight( AspireML.db.global.window.height )	
	--frame:SetScript("OnHide", Frame_OnClose)
	--frame:SetScript("OnMouseDown", Frame_OnMouseDown)
	
	if AspireML.db.global.window.x ~= 0 and AspireML.db.global.window.y ~= 0 then
		frame:SetPoint(
			AspireML.db.global.window.point,
			UIParent,
			AspireML.db.global.window.relativePoint,
			AspireML.db.global.window.x, 
			AspireML.db.global.window.y
		)
	end
	
	local titlebg = frame:CreateTexture(nil, "OVERLAY")
	titlebg:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header")
	titlebg:SetTexCoord(0.31, 0.67, 0, 0.63)
	titlebg:SetPoint("TOP", 0, 12)
	titlebg:SetWidth(100)
	titlebg:SetHeight(40)

	local title = CreateFrame("Frame", nil, frame)
	title:EnableMouse(true)
	title:SetScript("OnMouseDown", function( f )
		f:GetParent():StartMoving()
	end)
	title:SetScript("OnMouseUp", function( f )
		f:GetParent():StopMovingOrSizing()
	end)
	title:SetAllPoints(titlebg)
	
	local titletext = title:CreateFontString(nil, "OVERLAY", "GameFontNormal")
	titletext:SetPoint("TOP", titlebg, "TOP", 0, -14)
	titletext:SetText("AspireML " .. AspireML.VERSION)

	local titlebg_l = frame:CreateTexture(nil, "OVERLAY")
	titlebg_l:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header")
	titlebg_l:SetTexCoord(0.21, 0.31, 0, 0.63)
	titlebg_l:SetPoint("RIGHT", titlebg, "LEFT")
	titlebg_l:SetWidth(30)
	titlebg_l:SetHeight(40)

	local titlebg_r = frame:CreateTexture(nil, "OVERLAY")
	titlebg_r:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header")
	titlebg_r:SetTexCoord(0.67, 0.77, 0, 0.63)
	titlebg_r:SetPoint("LEFT", titlebg, "RIGHT")
	titlebg_r:SetWidth(30)
	titlebg_r:SetHeight(40)
	
	local sizer_se = CreateFrame("Frame", nil, frame)
	sizer_se:SetPoint("BOTTOMRIGHT")
	sizer_se:SetWidth(25)
	sizer_se:SetHeight(25)
	sizer_se:EnableMouse()
	sizer_se:SetScript("OnMouseDown", function( f ) 
		f:GetParent():StartSizing("BOTTOMRIGHT")
	end)
	sizer_se:SetScript("OnMouseUp", function( f ) 
		f:GetParent():StopMovingOrSizing()
	end)

	local line1 = sizer_se:CreateTexture(nil, "BACKGROUND")
	line1:SetWidth(14)
	line1:SetHeight(14)
	line1:SetPoint("BOTTOMRIGHT", -8, 8)
	line1:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
	local x = 0.1 * 14/17
	line1:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5)

	local line2 = sizer_se:CreateTexture(nil, "BACKGROUND")
	line2:SetWidth(8)
	line2:SetHeight(8)
	line2:SetPoint("BOTTOMRIGHT", -8, 8)
	line2:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
	local x = 0.1 * 8/17
	line2:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5)
	
	
	return frame

end


function BidsGui:CreateButton( label )

	self.buttons = self.buttons + 1

	local frame = CreateFrame("Button", "button" .. self.buttons, UIParent, "UIPanelButtonTemplate2")

	frame:EnableMouse(true)
	frame:SetHeight(24)
	frame:SetWidth(200)	

	local text = frame:GetFontString()
	text:ClearAllPoints()
	text:SetPoint("TOPLEFT", 15, -1)
	text:SetPoint("BOTTOMRIGHT", -15, 1)
	text:SetJustifyV("MIDDLE")
	text:SetText(label)
	
	return frame
end


function BidsGui:CreateScrollFrame( parent )

	self.scrollbars = self.scrollbars + 1

	local scrollframe = CreateFrame("ScrollFrame", nil, parent)	

	local scrollbar = CreateFrame("Slider", "AspireML_Scrollbar_" .. self.scrollbars, scrollframe, "UIPanelScrollBarTemplate")
	scrollbar:SetPoint("TOPLEFT", scrollframe, "TOPRIGHT", 4, -16)
	scrollbar:SetPoint("BOTTOMLEFT", scrollframe, "BOTTOMRIGHT", 4, 16)
	scrollbar:SetMinMaxValues(0, 1000)
	scrollbar:SetValueStep(1)
	scrollbar:SetValue(0)
	scrollbar:SetWidth(16)
	--scrollbar:Hide()	
	

	local scrollbg = scrollbar:CreateTexture(nil, "BACKGROUND")
	scrollbg:SetAllPoints(scrollbar)
	scrollbg:SetTexture(0, 0, 0, 0.4)

	--Container Support
	local content = CreateFrame("Frame", nil, scrollframe)
	content:SetPoint("TOPLEFT")
	content:SetPoint("TOPRIGHT")
	content:SetHeight(400)
	scrollframe:SetScrollChild(content)

	scrollbar:SetScript("OnValueChanged", function (frame, value)
		BidsGui:SetScroll( value )
	end)

	return scrollframe, content
end

function BidsGui:SetScroll(value)

	local viewheight = self.frame.scrollframe:GetHeight()
	local height = self.frame.scrollcontainer:GetHeight()
	local offset

	if viewheight > height then
		offset = 0
	else
		offset = floor((height - viewheight) / 1000.0 * value)
	end
	self.frame.scrollcontainer:ClearAllPoints()
	self.frame.scrollcontainer:SetPoint("TOPLEFT", 0, offset)
	self.frame.scrollcontainer:SetPoint("TOPRIGHT", 0, offset)	
end


function BidsGui:CreateBidEntry( container, relativeTo )

	self.numentries = self.numentries + 1

	local entry = CreateFrame("CheckButton", "AspireML_Entry_"..self.numentries, container)
	entry:SetScript("OnClick", function( f ) 
		
		if f:GetChecked() then
			-- deselect current selection
			if BidsGui.selected then BidsGui.selected:SetChecked( false ) end
			BidsGui.selected = f			
		else
			BidsGui.selected = nil
		end		
	end)
	entry:SetHeight(20)
	
	if relativeTo then
		entry:SetPoint( "TOP", relativeTo, "BOTTOM" )
	else
		entry:SetPoint( "TOP" )
	end		
		
	entry:SetPoint( "LEFT", container, "LEFT", 5, 0 )
	entry:SetPoint( "RIGHT" )

	entry:SetHighlightTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight")
	entry:SetCheckedTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight")
	entry:GetHighlightTexture():SetBlendMode("ADD")	
	entry.line1 = entry:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
	entry.line1:SetPoint("LEFT", 0 ,0)
	entry.line1:SetPoint("RIGHT", -5, 0)
	entry.line1:SetJustifyH("LEFT")
	entry:Hide()
	
	
	--entry.line1:SetText( "[" .. AspireML:GetColoredName( unitname ).. "]: " .. message )
	
	--	entry:SetScript("OnEnter", OnEnter)
	--	entry:SetScript("OnLeave", OnLeave)
	return entry

end


function BidsGui:CreateIconAndLabel( topframe )

	local frame = CreateFrame("Button", nil, topframe)

	frame:EnableMouse(true)
	frame:SetHeight( 32 )
	--frame:SetScript("OnEnter", Control_OnEnter)
	--frame:SetScript("OnLeave", Control_OnLeave)
	--frame:SetScript("OnClick", Button_OnClick)

	local image = frame:CreateTexture(nil, "BACKGROUND")
	image:SetWidth(32)
	image:SetHeight(32)
	image:SetPoint("TOPLEFT", 0, -5)

	local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlight")
	label:SetPoint("LEFT", image, "RIGHT" )
	label:SetJustifyH("LEFT")
	label:SetJustifyV("CENTER")
	label:SetHeight(32)	
	label:SetFont( "Fonts\\FRIZQT__.TTF", 15 );

	local highlight = frame:CreateTexture(nil, "HIGHLIGHT")
	highlight:SetAllPoints(image)
	highlight:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight")
	highlight:SetTexCoord(0, 1, 0.23, 0.77)
	highlight:SetBlendMode("ADD")

	return frame, image, label
end